import { Inject, Provide, httpError } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { NUser } from "../entity/user.entity";
import * as bcryptjs from 'bcryptjs';
import { JwtService } from "@midwayjs/jwt";
@Provide()
export class LoginService {
    @InjectEntityModel(NUser)
    userRepository: Repository<NUser>;

    @Inject()
    jwtService: JwtService;


    //注册逻辑
    async register(user: NUser) {
        const findRes = await this.userRepository.findOne({
            where: {
                account: user.account,
            },
        });
        if (findRes) return new httpError.BadRequestError('用户已存在');

        user.passwd = bcryptjs.hashSync(user.passwd, 10);
        return this.userRepository.save(user);

    }


    // 登录用户查询
    async login(user: NUser) {
        const findRes = await this.userRepository.findOne({
            where: {
                account: user.account
            },
        });
        if (!findRes) return new httpError.BadRequestError('不存在该用户');
        const compareRes: boolean = bcryptjs.compareSync(
            user.passwd,
            findRes.passwd
        );
        if (!compareRes) return new httpError.BadRequestError('密码错误');
        const token = this.jwtService.signSync({ id: user.id, name: user.name });
        return {
            accessToken: token,
        };
    }

}